package com.liuche.homechat.common.user.service.handler;

import com.liuche.homechat.common.user.service.WXMsgService;
import com.liuche.homechat.common.user.service.adapter.TextBuilder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
@Slf4j
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private WXMsgService wxMsgService;

    /**
     * 用户订阅消息通知处理
     * @param wxMessage
     * @param context
     * @param weixinService
     * @param sessionManager
     * @return
     * @throws WxErrorException
     */
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        log.info("新用户关注 OPENID：{};eventKey：{}", wxMessage.getFromUser(), wxMessage.getEventKey());
        String eventKey = wxMessage.getEventKey();
        if (StringUtils.hasLength(eventKey)) {
            return wxMsgService.handleScan(wxMessage, context, weixinService, sessionManager);
        }
        return TextBuilder.build("你好啊，欢迎关注帅帅测试号", wxMessage);
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpService weixinService, WxMpXmlMessage wxMessage)
            throws Exception {
        log.info("特殊处理，wxMessage->[{}]", wxMessage);
        return null;
    }

}
